package com.mg.admin.util;

import com.xiaoleilu.hutool.io.FileUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.jnlp.FileContents;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;


public class FileUtils {
public static Log log = LogFactory.getLog(FileUtils.class);


	public static String uploadFile(HttpServletRequest request,String directory) {
		String path = "";
		//解析器解析request的上下文
		CommonsMultipartResolver multipartResolver =
				new CommonsMultipartResolver(request.getSession().getServletContext());
		//先判断request中是否包涵multipart类型的数据，
		if (multipartResolver.isMultipart(request)) {
			//再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator iter = multiRequest.getFileNames();
			String realPath = request.getSession().getServletContext().getRealPath("");
			String root = realPath.substring(0,realPath.lastIndexOf(File.separator));
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					//String fileType = file.getContentType();
					//重命名上传后的文件名,使用时间戳作为文件名称
					//fileName = System.currentTimeMillis()+String.valueOf(new Random().nextInt(10000))+extName;

					path = File.separator + "upload" + File.separator + directory + File.separator + fileName;
					File localFile = new File(root + path);
					//写文件到本地
					try {
						file.transferTo(localFile);
					} catch (IOException e) {
						log.info(e.getMessage());
					}

				}
			}
		}
		return path;
	}


	public static void main(String[] args) {
		String path = "/opt/tomcat/webapps/ROOT";
		System.out.println(path.substring(0,path.lastIndexOf("/")));
	}


}
